package com.gzx.plugin.data.wxjk.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.gzx.plugin.data.wxjk.entity.DataWxjkSssj;
import com.gzx.plugin.data.wxjk.mapper.DataWxjkSssjMapper;
import com.gzx.plugin.data.wxjk.service.IDataWxjkSssjService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.consts.IntConstant;
import vip.xiaonuo.common.util.CommonDateUtil;
import vip.xiaonuo.common.util.CommonSleepUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zjt
 * @description
 * @date 2025/2/12 17:56
 */
@Service
@DS("data")
@RequiredArgsConstructor
public class DataWxjkSssjServiceImpl implements IDataWxjkSssjService {

    private final DataWxjkSssjMapper dataWxjkSssjMapper;

    private final CommonCacheOperator cacheOperator;

    /**
     * 是否开始同步数据
     *
     * @return
     */
    @Override
    public boolean isStartSynchronization() {
        String maxTime = dataWxjkSssjMapper.getMaxTime(CommonDateUtil.getCurrentMonthFirstDay());
        if (CommonDateUtil.isAfterMinutes(maxTime, -30)) {
            return true;
        }
        return false;
    }

    /**
     * 获取当前月份所有数据ID
     *
     * @return
     */
    @Override
    public List<Long> getCurrentMonthIdList() {
        List<DataWxjkSssj> dataWxjkSssjList = dataWxjkSssjMapper.selectList(Wrappers.<DataWxjkSssj>lambdaQuery()
                .select(DataWxjkSssj::getId)
                .gt(DataWxjkSssj::getCreateTime, CommonDateUtil.getCurrentMonthFirstDay()));
        if (CollectionUtil.isNotEmpty(dataWxjkSssjList)) {
            return dataWxjkSssjList.stream().map(DataWxjkSssj::getId).toList();
        }
        return List.of();
    }

    /**
     * 通过ID获取所有数据
     *
     * @param idList
     * @return
     */
    @Override
    public List<DataWxjkSssj> getAllDataByIdList(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return List.of();
        }
        List<DataWxjkSssj> dataWxjkSssjList = new ArrayList<>();
        List<List<Long>> batchIdList = Lists.partition(idList, 1000);
        for (List<Long> batchId : batchIdList) {
            dataWxjkSssjList.addAll(dataWxjkSssjMapper.selectBatchIds(batchId));
            CommonSleepUtil.sleep(IntConstant.VALUE_200);
        }
        return dataWxjkSssjList;
    }
}
